﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Service;
using MODEL;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using System.Windows.Input;
using GalaSoft.MvvmLight.Command;
using System.ComponentModel;
using Common;
using Microsoft.Practices.ServiceLocation;
using GalaSoft.MvvmLight.Views;

namespace ViewModel.PictureInfo
{
    public class AreaWeatherPictureViewModel : ViewModelBase
    {
        public ICommand PictureDetailCommand { get; set; }
        public ICommand PictureAddCommand { get; set; }
        public ICommand PictureUpdateCommand { get; set; }
        public ICommand PictureDeteleCommand { get; set; }

        private List<AreaWeatherPicture> m_AreaWeatherPictureList;
        public List<AreaWeatherPicture> AreaWeatherPictureList
        {
            get { return this.m_AreaWeatherPictureList; }
            set { this.m_AreaWeatherPictureList = value; base.RaisePropertyChanged(()=>this.AreaWeatherPictureList); }
        }

        private readonly Town m_NonSelectTown = new Town { TownName = "未选中乡镇" };
        private Town m_CurrentTown;
        public Town CurrentTown
        {
            get { return this.m_CurrentTown; }
            set { this.m_CurrentTown = value; base.RaisePropertyChanged(() => CurrentTown); }
        }
        private List<Town> m_TownList;
        public List<Town> TownList
        {
            get { return this.m_TownList; }
            set { this.m_TownList = value;base.RaisePropertyChanged(() => TownList); }
        }
      
        
        private IPictureInfoService m_PictureInfoService;

        private IAreaService m_AreaService;

        public AreaWeatherPictureViewModel(IPictureInfoService pictureInfoService, IAreaService areaService)
        {
            this.m_PictureInfoService = pictureInfoService;
            this.m_AreaService = areaService;
            this.PictureAddCommand = new RelayCommand(ShowAddImageForm);
            this.PictureUpdateCommand = new RelayCommand<AreaWeatherPicture>(ShowUpdateImageForm);
            this.PictureDeteleCommand = new RelayCommand<int>(DeleteWeatherPicture);

            RefreshData(() => this.PropertyChanged += OnPropertyChange);
        }

        public void OnPropertyChange(object sender, PropertyChangedEventArgs e)
        {      

            if (e.PropertyName == "CurrentTown")
            { 
                QueryAreaWeatherPicture();
            }
        }

        public async void RefreshData(Action afterAction = null)
        {
            try
            {
                List<Town> towns = new List<Town>() { this.m_NonSelectTown };
                towns.AddRange(await m_AreaService.GetTownList());
                this.TownList = towns;

                this.CurrentTown = this.m_NonSelectTown;

                QueryAreaWeatherPicture();

                if (afterAction != null)
                {
                    afterAction.Invoke();
                }
            }
            catch (Exception ex)
            {
                await ServiceLocator.Current.GetInstance<IDialogService>().ShowError("加载数据失败", "错误", "确定", null);
                Log.WriteException(ex);
            }
        }

        private async void QueryAreaWeatherPicture()
        {           
            try
            {
                List<AreaWeatherPicture> areaWeatherPictureList;
                if (this.CurrentTown==null || this.CurrentTown == this.m_NonSelectTown)
                {
                    areaWeatherPictureList = (await m_PictureInfoService.QueryAreaWeatherPictures(null)).ToList();
                }
                else
                {
                    areaWeatherPictureList = (await m_PictureInfoService.QueryAreaWeatherPictures(this.CurrentTown.TownId)).ToList();
                }

                areaWeatherPictureList.ForEach(pic => pic.PictureURL = AppSetting.Instance.GetWeatherPictureHttpUrl.SafeUrlEnd() + pic.PictureURL);
                this.AreaWeatherPictureList = areaWeatherPictureList;
            }
            catch (Exception ex)
            {
                await ServiceLocator.Current.GetInstance<IDialogService>().ShowError("获取图片信息", "错误", "确定", null);
                Log.WriteException(ex);
            }
        }

        private void ShowUpdateImageForm(AreaWeatherPicture areaWeatherPicture)
        {
            UploadAreaWeatherPictureViewModel vm = new UploadAreaWeatherPictureViewModel(this.m_PictureInfoService, this.m_AreaService) {
                AreaWeatherPicture = areaWeatherPicture,
                ParentViewModel = this
            };

            this.MessengerInstance.Send<ViewModelBase>(vm, "AreaWeatherPicture_ShowUploadForm");
        }

        private void ShowAddImageForm()
        {
            UploadAreaWeatherPictureViewModel vm = new UploadAreaWeatherPictureViewModel(this.m_PictureInfoService, this.m_AreaService)
            {
                ParentViewModel = this
            };

            this.MessengerInstance.Send<ViewModelBase>(vm, "AreaWeatherPicture_ShowUploadForm");
        }

        private async void DeleteWeatherPicture(int id)
        {
            bool isComfirm = await ServiceLocator.Current.GetInstance<IDialogService>().ShowMessage("所选数据将被删除，是否确认？", "提示", "确认", "删除", null);
            if (!isComfirm)
            {
                return;
            }
            try
            {
                Task task = this.m_PictureInfoService.DeleteAreaWeatherPicture(new List<int> { id });
                task.Wait();
                await ServiceLocator.Current.GetInstance<IDialogService>().ShowMessage("删除成功", "提示");
            }
            catch (Exception ex)
            {
                await ServiceLocator.Current.GetInstance<IDialogService>().ShowError($"删除失败: {ex.Message}", "错误", "确定", null);
            }
            RefreshData();         
        }
    }
}
